package com.tuanbiao.presenter;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.abiao.lib_utils.VibratorUtils;
import com.hjq.toast.ToastUtils;
import com.hzjq.data.callback.OnResultVoltageElectricProgressCallback;
import com.hzjq.data.entity.BlastEntity;
import com.hzjq.data.entity.SettingParams;
import com.hzjq.lib.BlastKool;
import com.hzjq.lib.cap.bean.CommResult;
import com.hzjq.lib.cap.bean.ErrorCap;
import com.hzjq.lib.checker.CheckError;
import com.tuanbiao.base.mvp.BasePresenter;
import com.tuanbiao.controllers.BlastController;
import com.tuanbiao.keyevent.KeyEventHelper;
import com.tuanbiao.utils.LibCollections;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/4/25 15:15
 */
public class BlastPresenter extends BasePresenter<BlastController.Model, BlastController.View> implements BlastController.Presenter {
    private Disposable disposable;
    //正在充电
    private boolean isCharging;
    private boolean isChargeSuccess;
    //正在爆破
    private boolean isBlasting;
    //是否爆破成功
    private boolean isBlastSuccess;
    private String errorMsg = "充电异常";
    private List<ErrorCap> mErrorCaps;
    private List<ErrorCap> mDuplicateCaps;
    private List<ErrorCap> mMissCaps;

    private BlastEntity blastEntity = null;

    public BlastPresenter(BlastController.Model model, BlastController.View rootView) {
        super(model, rootView);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    @Override
    public void charge() {
        mModel.cancelNetted();
        isCharging = true;
        mRootView.startCharge();
        mModel.charge(new OnResultVoltageElectricProgressCallback<CommResult>() {
            @Override
            public void onVoltageElectricChanged(float v, float v1) {
//                Timber.i("onVoltageElectricChanged#" + v + ",v1:" + v1);
                mRootView.showVoltageElectric(v, v1);
            }

            @Override
            public void onProgressChanged(@NonNull String s, int i, int i1) {
                Timber.i("onProgressChanged#" + i + ",s:" + s + ",i1:" + i1);
                mRootView.showProgress(i, s);
            }

            @Override
            public void onResult(CommResult commResult) {
                isCharging = false;
                Timber.i("onResult#" + commResult.isSuccess());
                isChargeSuccess = commResult.isSuccess();

                if (isChargeSuccess) {
                    errorMsg = "充电成功";
//                    startInterval();

                } else {
                    mErrorCaps = commResult.getFailedCaps();
                    mDuplicateCaps = commResult.getMeetErrorCaps();
                    mMissCaps = commResult.getMissErrorCaps();
                }
                if (isChargeSuccess) {
                    mRootView.chargeFinish(isChargeSuccess, createChargeMsg(commResult));
                } else  {
                    if(commResult.isAllCapError() || isContainMeetOrAuth()){
                        mRootView.chargeFinish(isChargeSuccess, createChargeMsg(commResult));
                    } else {
                        mRootView.chargeError(createChargeNextMsg(commResult));
                    }
                }
            }

            @Override
            public void onFailed(@NonNull String s) {
                isCharging = false;
                Timber.e("onFailed#" + s);
                errorMsg = s;
                mRootView.chargeFailed(KeyEventHelper.getInstance().getChargeNoteFailed(s));
            }
        });
    }

    private boolean isContainMeetOrAuth(){
        SettingParams params = BlastKool.Companion.loader().quick().getSettings();
        if(!params.isForceBlastCheck()){
            return true;
        }
        if(!mDuplicateCaps.isEmpty() || !mMissCaps.isEmpty()){
            return true;
        }
        for (int i = 0; i < mErrorCaps.size(); i++) {
            BlastKool.Companion.addBlastLog("充电E "+mErrorCaps.get(i).getCap().getCap().getConvertUid());
        }
        return false;
    }

    private void startInterval() {
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        Timber.i("interval:" + aLong);
                        if (aLong == 60) {
                            disposable.dispose();
                            exit();
                        }
                    }
                });
        addDispose(disposable);
    }

    private String createChargeNextMsg(CommResult result){
        int count = LibCollections.size(result.getFailedCaps()) + LibCollections.size(result.getMissErrorCaps())
                + LibCollections.size(result.getMeetErrorCaps());
        if (count == 0) {
            return "充电异常";
        }
        return count + "发雷管充电异常，" + KeyEventHelper.getInstance().getChargeNoteFailed()+"，请记住异常雷管编号并退出充电页面，30分钟后再进入爆区检测异常雷管，如继续可能造成拒爆，请谨慎操作！";
    }


    private String createChargeMsg(CommResult result) {
        if (result.isSuccess()) {
            return KeyEventHelper.getInstance().getChargeNoteSuccess();
        } else {
            if (result.isAllCapError()) {
                return "所有雷管都充不上电！请退出充电页面，等待30分钟后再进入爆区检测异线路或雷管漏电原因";
            } else {
                int count = LibCollections.size(result.getFailedCaps()) + LibCollections.size(result.getMissErrorCaps())
                        + LibCollections.size(result.getMeetErrorCaps());
                if (count == 0) {
                    return "充电异常";
                }
                return count + "发雷管充电异常，" + KeyEventHelper.getInstance().getChargeNoteFailed()+"，请记住异常雷管编号并退出充电页面，30分钟后再进入爆区检测异常雷管";
            }
        }
    }

    @Override
    public void exitCharge() {
        mRootView.showLoading();
        mModel.exitCharge(aBoolean -> {
            mRootView.hideLoading();
            if (aBoolean) mRootView.killMyself();
            else mRootView.showMessage("退出失败，请重试！");
        });
    }

    @Override
    public void cancelCharge() {
        mModel.cancelCharge();
    }

    @Override
    public void forceBlast() {
        isCharging = false;
        isChargeSuccess = true;
        isBlasting = false;
        blast();
    }

    @Override
    public void blast() {
        if (isCharging) {
            mRootView.showMessage("正在充电中");
            return;
        }
        if (!isChargeSuccess) {
            mRootView.showMessage("充电异常，请按F2查看异常信息");
            return;
        }
        if (isBlasting) {
            mRootView.showMessage("正在爆破中，请勿重试！");
            return;
        }
        cancelCharge();
        isBlasting = true;
        blastEntity = null;
        VibratorUtils.Vibrate(2000L);
        mModel.blastCheck(error -> {
            if (error.getErrorCode() == CheckError.CHECK_SUCCESS) {
                mRootView.showProgress(0, "正在起爆");
                mRootView.startBlast();
                mModel.blast(new OnResultVoltageElectricProgressCallback<CommResult>() {

                    @Override
                    public void onVoltageElectricChanged(float v, float v1) {
                        Timber.i("blast#onVoltageElectricChanged#v:" + v + ",v1:" + v1);
                        mRootView.showVoltageElectric(v, v1);
                    }

                    @Override
                    public void onProgressChanged(@NonNull String s, int i, int i1) {
                        Timber.i("blast#onProgressChanged#s" + s + ",i：" + i + ",i1:" + i1);
                        mRootView.showProgress(i, s);
                    }

                    @Override
                    public void onResult(CommResult commResult) {
                        Timber.i("blast#onResult#commResult:" + commResult.isSuccess() + ",errorCaps:" + LibCollections.size(commResult.getFailedCaps()));
                        isBlasting = false;
                        blastEntity = commResult.getBlast();
                        mErrorCaps = commResult.getFailedCaps();
                        mDuplicateCaps = commResult.getMeetErrorCaps();
                        mMissCaps = commResult.getMissErrorCaps();
                        isBlastSuccess = commResult.isSuccess();
                        //createBlastMsg(isBlastSuccess,commResult.getForceAuthErrorCaps());
                        mRootView.blastFinish(isBlastSuccess, isBlastSuccess ? KeyEventHelper.getInstance().getBlastNoteSuccess() :
                                KeyEventHelper.getInstance().getBlastNoteFailed());
                    }

                    @Override
                    public void onFailed(@NonNull String s) {
                        isBlastSuccess = false;
                        isBlasting = false;
                        errorMsg = s;
                        Timber.e("blast#onFailed#s:" + s);
                        mRootView.blastFailed(KeyEventHelper.getInstance().getBlastNoteFailed(s));
                    }
                });
            } else {
                mRootView.showMessage(error.getErrorMsg());
            }
        });
    }

    private String createBlastMsg(boolean isBlastSuccess,List<ErrorCap> errorCaps) {
        if(isBlastSuccess && !errorCaps.isEmpty()){
            for (int i = 0; i < errorCaps.size(); i++) {
                BlastKool.Companion.addBlastLog("起爆E "+errorCaps.get(i).getCap().getCap().getConvertUid());
            }
        }
        return null;
    }

    @Override
    public void cancelBlast() {
        mModel.cancelBlast();
    }

    @Override
    public void exitBlast() {
        mModel.exitBlast();
    }

    @Override
    public void exit() {
        Timber.i("blast#exit#s:" + isBlasting);
        if (isBlasting) {
            ToastUtils.show("爆破中，请勿操作...");
            return;
        }
       // cancelCharge();
        exitCharge();
    }

    @Override
    public boolean isBlastSuccess() {
        return isBlastSuccess;
    }

    @Override
    public void checkErrorCaps() {
        if (isCharging) {
//            mRootView.showMessage("正在充电");
            return;
        }

        if (isBlasting) {
//            mRootView.showMessage("正在爆破");
            return;
        }
        if (LibCollections.isEmpty(mErrorCaps) && LibCollections.isEmpty(mDuplicateCaps) && LibCollections.isEmpty(mMissCaps)) {
            mRootView.showMessage(errorMsg);
        } else {
            List<ErrorCap> errorCaps = new ArrayList<>();
            if (null != mErrorCaps) errorCaps.addAll(mErrorCaps);
            if (null != mDuplicateCaps) errorCaps.addAll(mDuplicateCaps);
            if (null != mMissCaps) errorCaps.addAll(mMissCaps);
            mRootView.startErrorCap(errorCaps);
        }

    }

    @Override
    public void startUpload() {
        if (null != blastEntity) {
            mRootView.startUpload(blastEntity);
        }
    }
}
